<template>
    <div class="bodyBox">
        <div class="bodyType">
            <el-row :gutter="5">
                <el-col :span="22" style="padding-left: 20px;">
                    <el-radio-group v-model="radio">
                        <el-radio :label="0">JSON</el-radio>
                        <el-radio :label="1">Form-data</el-radio>
                    </el-radio-group>
                </el-col>
                <el-col :span="2" style="text-align: center;">
                    <el-button v-if="radio == 1" @click="addItem" icon="el-icon-plus" size="mini" circle type="success">
                    </el-button>
                </el-col>
            </el-row>
        </div>
        <div class="body_textarea_box" v-show="radio == 0" :style="{'height':height - 40 + 'px' }">
            <textarea ref="body"></textarea>
        </div>
        <quickInsert style="top:40px" :editor="editor" v-show="radio == 0" :format="formatJson"></quickInsert>
        <div class="body_from_box" v-show="radio == 1">
            <formItem v-for="(item, index) in fromArray" :deleteEvent="formItemDelete" :formitem="item" :index="index"
                :changeEvent="formItemChange" :key="index">
            </formItem>
        </div>
    </div>
</template>
<script>

    import { mapState } from 'vuex';
    import formItem from './fromItem'
    import quickInsert from './quickInsert';

    let CodeMirror = require("codemirror/lib/codemirror");
    import "codemirror/lib/codemirror.css";
    import "codemirror/theme/mdn-like.css";
    import "codemirror/mode/javascript/javascript.js";
    import "codemirror/addon/fold/foldgutter.css";
    import "codemirror/addon/fold/foldcode.js";
    import "codemirror/addon/fold/foldgutter.js";
    import "codemirror/addon/fold/brace-fold.js";
    import "codemirror/addon/fold/comment-fold.js";
    import "codemirror/addon/edit/matchbrackets";
    import 'codemirror/addon/hint/javascript-hint'
    import 'codemirror/addon/hint/show-hint'
    import 'codemirror/keymap/sublime.js'
    import 'codemirror/keymap/emacs.js'
    import 'codemirror/keymap/vim.js'

    export default {
        components: {
            formItem,
            quickInsert,
        },
        props: ['height', 'body', 'bodyType', 'fromdataValue', 'ChangeValue'],
        data() {
            return {
                fromArray: [],
                radio: this.bodyType,
                editor: null,
            }
        },
        watch: {
            radio(newValue) {
                this.ChangeValue('bodyType', newValue);
                this.$nextTick(() => {
                    this.refreshEditor();
                });
            },
        },
        mounted() {
            this.editor = CodeMirror.fromTextArea(this.$refs.body, {
                mode: 'text/javascript',
                indentWithTabs: true,
                smartIndent: false,
                lineNumbers: true,
                lineWrapping: true,
                foldGutter: true,
                matchBrackets: true,
                gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                theme: 'mdn-like',
            });
            this.editor.on('beforeChange', (instance, changeObj) => {
                if (changeObj.origin == '+input' && (changeObj.text == '\'' || changeObj.text == '\"')) {
                    var _str = this.editor.getSelection();
                    if (_str.toString().length > 0) {
                        this.editor.replaceSelection(_str + _str + changeObj.text);
                    };
                    // console.log(true);
                };
            });
            this.renderData();
        },
        methods: {
            ChangeEvent() {
                this.ChangeValue('body', this.editor.getValue());
            },
            closeChange() {
                this.editor.off('change', this.ChangeEvent);
            },
            restore() {
                this.renderData();
            },
            renderData() {
                this.editor.setValue(this.body);
                if (this.fromdataValue) {
                    this.fromArray = JSON.parse(this.fromdataValue);
                } else {
                    this.fromArray = [];
                };
                var _index = this.fromArray.length - 1;
                if (_index == -1) {
                    this.fromArray.push({
                        value: '',
                        type: 'text',
                        key: '',
                        url: '',
                    });
                };
                this.$nextTick(() => {
                    this.editor.on('change', this.ChangeEvent);
                });

            },
            addItem() {
                this.fromArray.push({
                    value: '',
                    type: 'text',
                    key: '',
                    url: '',
                });
                this.ChangeValue('fromdata', JSON.stringify(this.fromArray));
            },
            formItemChange(index) {
                // this.ChangeValue('body', this.editor.getValue());
                this.ChangeValue('fromdata', JSON.stringify(this.fromArray));
            },
            formItemDelete(index) {
                this.fromArray.splice(index, 1);
                if (this.fromArray.length == 0) {
                    this.fromArray.push({
                        value: '',
                        type: 'text',
                        key: ''
                    });
                };
                this.ChangeValue('fromdata', JSON.stringify(this.fromArray));
            },
            refreshEditor() {
                this.editor.refresh();
            },
            formatJson() {
                var str = this.editor.getValue();
                str = this.beautify(str);
                this.editor.setValue(str);
            },
            beautify(source) {
                function looks_like_html(source) {
                    var trimmed = source.replace(/^[ \t\n\r]+/, '');
                    return trimmed && (trimmed.substring(0, 1) === '<');
                };
                var output,
                    opts = {
                        // brace_style : "expand"
                    };
                opts.indent_char = ' ';
                opts.preserve_newlines = "-1";
                if (looks_like_html(source)) {
                    output = html_beautify(source, opts);
                } else {
                    output = js_beautify(source, opts);
                };
                return output;
            },
        }

    }
</script>

<style>
    .bodyBox {
        position: relative;
        width: 100%;
        height: 100%;
    }

    .bodyType {
        padding: 5px;
        line-height: 29px;
        margin: 1px 0 0 0;
        height: 29px;
        border-bottom: 1px solid #E4E7ED;
    }

    .CodeMirror {
        height: 100%;
    }

    .body_textarea_box {
        position: absolute;
        right: 200px;
        left: 0px;
        top: 40px;
        bottom: 0px;
        border-right: 1px solid #E4E7ED;
    }

    .body_from_box {
        position: absolute;
        right: 0px;
        left: 0px;
        top: 40px;
        bottom: 0px;
        border-right: 1px solid #E4E7ED;
        background: #fff;
        z-index: 10;
        overflow-y: auto;
    }


    .bodyBox .formatBotton {
        position: absolute;
        top: 3px;
        right: 4px;
        z-index: 10;
    }
</style>